<?php
/**
 * Svick a Fast Simple Smart PHP FrameWork
 * Author: Tommy 863758705@qq.com
 * Link: http://svick.tomener.com/
 * Since: 2022
 */

namespace lib\wechat;

use lib\client\EmojiLib;
use Svick\Config\Config;
use Svick\Http\Client\Http;
use Svick\Log\Log;

class WechatLib
{
    /**
     * 获取openid和unionid
     *
     * @param $code
     * @return bool|mixed
     */
    public static function getOpenidByCode($code)
    {
        $config = Config::runtime('wechat.ma');

        $auth_url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $config['appid'] . '&secret=' . $config['secret'] . '&js_code=' . $code . '&grant_type=authorization_code';
        $res = Http::get($auth_url);
        if ($res->status() != 200) {
            return false;
        }
        $data = $res->array();
        if (!$data) {
            return false;
        }
        if (!isset($data['openid'])) {
            Log::single($data, 'getOpenidByCode.err');
            return false;
        }
        //session_key=pa7odA9XDMbQoWiRG7UBcA==&expires_in=7200&openid=oPlr50HwQQbZE7IkRUeu4TFrRuZg&unionid=oYr0z1IuaTF3BdQ36mpDzmGL0ZUL
        return $data;
    }

    /**
     * 处理微信用户昵称，过略掉emoji表情
     *
     * @param $nickname
     * @return string
     */
    public static function doNickname($nickname)
    {
        $nickname = EmojiLib::filter($nickname);
        if (empty($nickname)) {
            $nickname = 'sk_' . mt_rand(10000000, 99999999);
        }
        $nickname = mb_substr($nickname, 0, 16, 'UTF-8');
        return trim($nickname);
    }

    /**
     * 处理微信地区
     *
     * @param $str
     * @return string
     */
    public static function doRegion($str)
    {
        $ret = EmojiLib::checkHasEmoji($str);
        if ($ret) {
            return '';
        }
        return mb_substr($str, 0, 50, 'UTF-8');
    }
}
